<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.setOptions(this.chartData);
    },
    setOptions() {
      console.log(this.chart);
      this.chart.setOption({
        series: [
          {
            type: "pie",
            data: this.chartData.data,
            radius: ["45%", "55%"],
            label: {
              show: true,
              formatter: "{c|{c}个}{b|{b}}{d|{d}%}",

              rich: {
                b: {
                  padding: 5,
                  borderColor: "#8CBAFF",
                  borderWidth: 1,
                  borderRadius: 2,
                  color: "#418AF7",
                  fontSize: 18,
                  backgroundColor: "#EDF4FF",
                },
                c: {
                  color: "#2E3440",
                  fontSize: 18,
                  fontWeight: 500,
                  padding: 5,
                },
                d: {
                  color: "#707787",
                  fontSize: 18,
                  fontWeight: 500,
                  padding: 5,
                },
              },
            },
            tooltip: {
              show: false,
            },
          },
        ],
      });
    },
  },
};
</script>
